declare var AdvancedGeolocation:any;
declare var google;
 import { Geolocation } from '@ionic-native/geolocation';
 import { Component,NgZone,ViewChild,ElementRef } from "@angular/core/";
 import { App,NavController, Platform,AlertController } from 'ionic-angular';
 import { HttpClient,HttpHeaders } from '@angular/common/http'
 import { NativeStorage } from '@ionic-native/native-storage'; 
 import { MultiPickerModule } from 'ion-multi-picker';
 import { TranslateService } from '@ngx-translate/core';

 import { AppConfig } from '../../app/app.config';

 import { HomelistPage } from "../homelist/homelist";
 import { FilterPage } from "../filter/filter";
 import { MypostPage } from "./mypost/mypost";
 import { SearchPage } from "./search/search";
 import { ProductrentPage } from "../product/rent/rent";
 import { ProductservicePage } from "../product/service/service";
 import { ProductbuyPage } from "../product/buy/buy";
 import { ProductperPage } from "../product/per/per";
 import { LoginPage } from '../login/login';
 @Component({
   selector: 'page-home',
   templateUrl: 'home.html',
 })
 export class HomePage {
   @ViewChild('map_canvas') mapElement: ElementRef;
   show_type='List';
   map:any;
   selectedItem:number;
   params: Object;
   pushPage: any;
   filterPage: any;
   postPage: any;
   list:any;
   list_lst:any;
   list_copy:any;
   detail:any;
   detail_active:boolean;
   filter:any;
   page=1;
   dependentColumns:any;
   default='';
   src = AppConfig.getMainUrl();
   latlng:any;
   markers=[]
   sign_position=true
   constructor(
     private app:App,
     private navCtl:NavController,
     private zone:NgZone,
     private geo:Geolocation,
     private http:HttpClient,
     private platform:Platform,
     private stroge:NativeStorage,
     private translate: TranslateService,
     private alertCtrl:AlertController,
  ) {
    this.filter = {sortby:''};
    this.pushPage = HomelistPage;
    this.params = { id: 42 };
    this.filterPage = FilterPage;
    this.postPage = MypostPage;
    this.dependentColumns = [
      {
        options: [
          { text: 'Latest relese', value: 'addtime desc' },
          { text: 'Price ascending', value: 'price asc' },
          { text: 'Price descending', value: 'price desc' },
          { text: 'Area ascending', value: 'area asc' },
          { text: 'Area descending', value: 'area desc' },
        ]
      }
    ];
   translate.setDefaultLang('en')
    
}
  ionViewDidEnter(){
    this.stroge.getItem('lang').then(res=>{
        this.translate.use(res)
    })
  }
  picker(){
    this.filter.sortby = this.default;
    this.getData();
    this.markerAdd();
  }
  set_position(){
    this.map.setCenter({
      lat: this.latlng.lat,
      lng: this.latlng.lng
    });
  }
  toggle(){
    if(this.show_type==='List'){
      this.show_type='Map'
    }else{
      this.show_type='List'
      this.page = 1;
    }
  }
  chooseType(item:number){
    let arr = [];
    let arr_s = [];
    this.selectedItem = item;
    this.list_copy.forEach((ele,i) => {
      if(ele.cate==item){
        switch(ele.cate){
          case 1:
            ele.cateName='Rent'
            break
          case 2:
            ele.cateName='Buy'
            break
          case 3:
            ele.cateName='Rent per day'
            break
          case 4:
            ele.cateName='Service'
            break
        }
        switch(ele.price_unit){
          case 1:
            ele.price_unit='£'
            break
          case 2:
            ele.price_unit='€'
            break
          case 3:
            ele.price_unit='$'
            break
          case 4:
            ele.price_unit='¥'
            break
        }
        switch(ele.area_unit){
          case 1:
            ele.area_unit='sq.ft'
            break
          case 2:
            ele.area_unit='㎡'
            break
        }
        ele.img = 'url('+AppConfig.getMainUrl()+ele.full_logo+')';
        arr.push(ele)
      }
      if(i<5){
        arr_s.push(ele)
        if(i==4){
          this.list_lst = arr_s
          this.page = 1
        }
      }
    });
    this.list = arr;
    this.markerAdd();
    
  }
  alertb(title,subTitle){
    let alert = this.alertCtrl.create({
        title: title,
        subTitle: subTitle,
        buttons: ['OK']
    });
    alert.present();
  }
  goto(page:any){
    // this.stroge.getItem('token').then(()=>{
      this.app.getRootNav().push(page);
    // }).catch(()=>{
    //   this.alertb('Error','Please login first!');
    //   this.app.getRootNav().push(LoginPage);
    // })
  }
  ngAfterViewInit() {
    this.platform.ready().then(()=>{
      let t = this;
      let mapOptions = {
          center:new google.maps.LatLng(43.0741904, -88.2801122),
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          disableDefaultUI: true,
      };
      
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
      this.map.addListener('zoom_changed', function() {
        t.markerAdd()
      });
        
      if (this.platform.is('android')) {
        this.platform.ready().then(() => {
          AdvancedGeolocation.start((success) => {
            try {
              var jsonObject = JSON.parse(success);
              switch (jsonObject.provider) {
                case "gps":
                  if(!this.latlng) this.latlng = {lat:parseFloat(jsonObject.latitude),lng:parseFloat(jsonObject.longitude)}
                  AdvancedGeolocation.stop();
                  break;
                case "network":
                  if(!this.latlng) this.latlng = {lat:parseFloat(jsonObject.latitude),lng:parseFloat(jsonObject.longitude)}
                  AdvancedGeolocation.stop();
                  break;
                case "satellite":
                  
                  break;
                case "cell_info":
                  break;
                case "cell_location":
                  if(!this.latlng) this.latlng = {lat:parseFloat(jsonObject.latitude),lng:parseFloat(jsonObject.longitude)}
                  AdvancedGeolocation.stop();
                  break;
                case "signal_strength":
                  
                  break;
              }
              if(!this.list) this.setPosition(this.latlng)
            }
            catch (exc) {
              console.log("Invalid JSON: " + exc);
            }
            
          },function (error) {
              console.log("ERROR! " + JSON.stringify(error));
          },
          {
            "minTime": 30000,         // Min time interval between updates (ms)
            "minDistance": 100,       // Min distance between updates (meters)
            "noWarn": true,         // Native location provider warnings
            "providers": "all",     // Return GPS, NETWORK and CELL locations
            "useCache": true,       // Return GPS and NETWORK cached locations
            "satelliteData": false, // Return of GPS satellite info
            "buffer": false,        // Buffer location data
            "bufferSize": 0,         // Max elements in buffer
            "signalStrength": false // Return cell signal strength data
          })
         
        });
      } else {
        let options = {
          timeout:50000,
          enableHighAccuracy:true,
        };
        this.geo.getCurrentPosition(options).then((resp) => {
          this.setPosition({lat:resp.coords.latitude,lng:resp.coords.longitude})
          this.latlng = {lat:resp.coords.latitude,lng:resp.coords.longitude}
        }).catch(err=>{
          console.log(err)
        });
      }
    })
      
     
  }
  gotofilter(){
    this.app.getRootNav().push(this.filterPage,{callback:this.myCallbackFunction});
  }
  gotosearch(){
    this.app.getRootNav().push(SearchPage,{search:this.myCallbackFunction});
  }
  myCallbackFunction=(params)=> {
    return new Promise((resolve, reject) => {
      if(typeof(params)!='undefined'){
          resolve('ok');
          this.filter = params;
          this.selectedItem = params.cate;
          this.getData();
      }else{
          reject(Error('error'))
      }
            
    })
  }
  setPosition(latlng){
    let url = '';
    this.map.setCenter({
      lat: latlng.lat,
      lng: latlng.lng
    });
    this.stroge.setItem('latlng',latlng);
    // this.map.clearOverlays()
    let marker = new google.maps.Marker({
      animation: google.maps.Animation.DROP,
      position: {
        lat: latlng.lat,
        lng: latlng.lng
      }
    });
    marker.setMap(this.map);
    this.stroge.getItem('token').then((res)=>{
      url = AppConfig.getUrl()+'house/getall?lng='+latlng.lng+'&lat='+latlng.lat+'&token='+res;
      this.http.get(url).subscribe(res=>{
        if(res['code']==101){
          this.list = res['data'];
          this.list_copy = res['data'];
          this.datatodata();
          this.markerAdd();
        }
      })
    }).catch(()=>{
      url = AppConfig.getUrl()+'house/getall?lng='+latlng.lng+'&lat='+latlng.lat+'&token=';
      this.http.get(url).subscribe(res=>{
        if(res['code']==101){
          this.list = res['data'];
          this.list_copy = res['data'];
          this.datatodata();
          this.markerAdd();
        }
      })
    })
    this.stroge.setItem('latlng',[latlng.lat,latlng.lng])
  }
  
  markerAdd(){
    let zoom = this.map.getZoom(),sign
    if( zoom>12 ){
      sign = 1;
    }
    if( zoom<=12 && zoom>=10 ){
      sign = 2;
    }
    if( zoom<10 ){
      sign = 3;
    }
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(null);
    }
    let t = this,color;
    if(sign==1){
      for (let item of this.list) {
        let price,icon;
        switch(item.price_unit){
            case 1:
              price='£'+item.price;
              break
            case 2:
              price='€'+item.price;
              break
            case 3:
              price='$'+item.price;
              break
            case 4:
              price='¥'+item.price;
              break
            default:
              price='¥'+item.price;
        }
        switch(item.cate){
          case 1:
            icon ='./assets/icon/markerBlue.png';
            break
          case 2:
            icon='./assets/icon/markerGreen.png';
            break
          case 3:
            icon='./assets/icon/markerRed.png';
            break
          case 4:
            icon='./assets/icon/markerYellow.png';
            break
        }
        let marker = new google.maps.Marker({
            position: new google.maps.LatLng(item.latitude,item.longitude),
            icon: icon,
            map:this.map,
            label: {
              fontSize: '18px',
              color:'#fff',
              text: price
            }
        });
        marker.addListener('click', function() {
          t.zone.run(() => {
            t.map.setCenter({
              lat: item.latitude,
              lng: item.longitude
            });
            t.detail_active = true
            switch(item.price_type){
              case 1:
              item.price_type='Month'
                break
              case 2:
              item.price_type='Week'
                break
              case 3:
              item.price_type='Day'
                break
            }
            switch(item.area_unit){
              case 1:
                item.area_unit='SQ.FT'
                item.other_area = Math.ceil(item.area / 10.764);
                item.other_area_unit='SQ.M'
                break
              case 2:
                item.area_unit='SQ.M'
                item.other_area = Math.ceil(item.area * 10.764);
                item.other_area_unit='SQ.FT'
                break
            }
            t.detail = item
          });
        });
        this.markers.push(marker);
      }
    }
    if(sign==2){
        for (let item of this.list) {
          switch(item.cate){
            case 1:
              color="b"
              break
            case 2:
              color="g"
              break
            case 3:
              color="r"
              break
            case 4:
              color="y"
              break
          }
          let marker = new google.maps.Marker({
            position: new google.maps.LatLng(item.latitude,item.longitude),
            map: this.map,
            icon: './assets/icon/map_map_'+color+'.png',
          });
          marker.addListener('click', function() {
            t.zone.run(() => {
              t.map.setCenter({
                lat: item.latitude,
                lng: item.longitude
              });
              t.detail_active = true
              switch(item.price_type){
                case 1:
                item.price_type='Month'
                  break
                case 2:
                item.price_type='Week'
                  break
                case 3:
                item.price_type='Day'
                  break
              }
              switch(item.area_unit){
                case 1:
                  item.area_unit='SQ.FT'
                  item.other_area = Math.ceil(item.area / 10.764);
                  item.other_area_unit='SQ.M'
                  break
                case 2:
                  item.area_unit='SQ.M'
                  item.other_area = Math.ceil(item.area * 10.764);
                  item.other_area_unit='SQ.FT'
                  break
              }
              t.detail = item
            });
          });
          this.markers.push(marker);
        }
      }
      if(sign==3){
        for (let item of this.list) {
          switch(item.cate){
            case 1:
              color="b"
              break
            case 2:
              color="g"
              break
            case 3:
              color="r"
              break
            case 4:
              color="y"
              break
          }
          let marker = new google.maps.Marker({
            position: new google.maps.LatLng(item.latitude,item.longitude),
            map: this.map,
            icon: './assets/icon/map_dian_'+color+'.png',
          });
          marker.addListener('click', function() {
            t.zone.run(() => {
              t.map.setCenter({
                lat: item.latitude,
                lng: item.longitude
              });
              t.detail_active = true
              switch(item.price_type){
                case 1:
                item.price_type='Month'
                  break
                case 2:
                item.price_type='Week'
                  break
                case 3:
                item.price_type='Day'
                  break
              }
              switch(item.area_unit){
                case 1:
                  item.area_unit='SQ.FT'
                  item.other_area = Math.ceil(item.area / 10.764);
                  item.other_area_unit='SQ.M'
                  break
                case 2:
                  item.area_unit='SQ.M'
                  item.other_area = Math.ceil(item.area * 10.764);
                  item.other_area_unit='SQ.FT'
                  break
              }
              t.detail = item
            });
          });
          this.markers.push(marker);
        }
      }
      
  }
  getData(){
    let url = ''
    this.stroge.getItem('token').then((token)=>{
      url = AppConfig.getUrl()+'house/index?do=index'+AppConfig.urlEcode(this.filter)+'&token='+token;
      this.http.get(url).subscribe(res=>{
        this.map.setCenter({
          lat: Number(res['data']['rows'][0]['latitude']),
          lng: Number(res['data']['rows'][0]['longitude'])
        });
        this.list = res['data']['rows']
        this.list_copy = res['data']['rows']
        this.datatodata()
        this.markerAdd()
      })
    }).catch(()=>{
      url = AppConfig.getUrl()+'house/index?do=index'+AppConfig.urlEcode(this.filter);
      this.http.get(url).subscribe(res=>{
        this.map.setCenter({
          lat: Number(res['data']['rows'][0]['latitude']),
          lng: Number(res['data']['rows'][0]['longitude'])
        });
        this.list = res['data']['rows']
        this.list_copy = res['data']['rows']
        this.datatodata()
        this.markerAdd()
       
      })
    })
   
  }
  datatodata(){
    this.list_lst = [];
    this.list.forEach((item,i) => {
      switch(item.cate){
        case 1:
          this.list[i].cateName='Rent'
          break
        case 2:
          this.list[i].cateName='Buy'
          break
        case 3:
          this.list[i].cateName='Rent per day'
          break
        case 4:
          this.list[i].cateName='Service'
          break
      }
      switch(item.price_unit){
        case 1:
          this.list[i].price_unit='£'
          break
        case 2:
          this.list[i].price_unit='€'
          break
        case 3:
          this.list[i].price_unit='$'
          break
        case 4:
          this.list[i].price_unit='¥'
          break
      }
      switch(item.price_type){
        case 1:
          this.list[i].price_type='Month'
          break
        case 2:
          this.list[i].price_type='Week'
          break
        case 3:
          this.list[i].price_type='Day'
          break
      }
      switch(item.area_unit){
        case 1:
          this.list[i].area_unit='SQ.FT'
          this.list[i].other_area = Math.ceil(this.list[i].area / 10.764);
          this.list[i].other_area_unit='SQ.M'
          break
        case 2:
          this.list[i].area_unit='SQ.M'
          this.list[i].other_area = Math.ceil(this.list[i].area * 10.764);
          this.list[i].other_area_unit='SQ.FT'
          break
      }
      this.list[i].img = 'url('+AppConfig.getMainUrl()+item.logo+')';
      if(i<5){
        this.list.push(this.list[i]);
      }
    });
  }
  // doInfinite(infiniteScroll) {
  //   if(this.list.length>(this.page-1)*5){
  //     setTimeout(() => {
  //       for(let i=(this.page-1)*5;i<this.page*5;i++){
  //         this.list_lst.push(this.list[i])
  //       }
        
  //     },500)
  //     infiniteScroll.complete();
  //   }else{
  //     infiniteScroll.enable(false)
  //   }    
  // }
  save_search() {
    if(this.list.length==0){
      this.alertb('Error','No information under this search condition!');
      return false
    }
    
    let alert = this.alertCtrl.create({
      title: 'Name your search',
      inputs: [
        {
          name: 'name',
          placeholder: ''
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'OK',
          handler: data => {
            if (data.name!='') {
              this.stroge.getItem('token').then(res=>{
                this.http.post(AppConfig.getUrl()+'house/savesearch?token='+res,AppConfig.urlEcode({'name':data.name,"json":JSON.stringify(this.filter)}),{ headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe(resp=>{
                  if(data.code==101){
                    this.alertb('Sava successed!','');
                  }else{
                    this.alertb(resp['msg'],'');
                  }
                })
              }).catch(()=>{
                this.alertb('Error','Please login first!');
                this.app.getRootNav().push(LoginPage);
              })
              
            } else {
              // invalid login
              return false;
            }
          }
        }
      ]
    });
    alert.present();
  }
  goDetail(item:any){
    let page
    switch(item.cate){
      case 1:
        page = ProductrentPage
        break
      case 2:
        page = ProductbuyPage
        break
      case 3:
        page = ProductperPage
        break
      case 4:
        page = ProductservicePage
        break
    }
    this.app.getRootNav().push(page,{id:item.id})
  }
  
 }